﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Quick.EntityFrameworkCore.Options;

namespace Microsoft.Extensions.DependencyInjection;

public static class ServiceProviderExtensions
{
    public static void AutoConfigure<T>(this IServiceProvider serviceProvider, DbContextOptionsBuilder optionsBuilder)
        where T : DbContext
    {
        var logger = serviceProvider.GetService<ILogger<DbContextOptionsBuilder>>();

        var providerKeyAccessor = serviceProvider.GetRequiredService<IProviderNameAccessor>();

        var key = providerKeyAccessor.Get();

        logger?.LogDebug("Provider Key: {Value}", key);

        var provider = serviceProvider.GetRequiredKeyedService<IEntityFrameworkCoreDatabaseOptionsProvider>(key);

        logger?.LogDebug("Provider: {Value}", provider);

        provider.Configure<T>(serviceProvider, optionsBuilder);
    }
}
